package com.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtils {
    /**
     * 目标目录里是否存在指定文件
     *
     * @param dir
     * @param fileName
     * @return
     */
    public static boolean isExistFile(File dir, String fileName) {
        if (!dir.exists()) {
            return false;
        }
        File[] fileNames = dir.listFiles();
        for (int i = 0; i < fileNames.length; i++) {
            if (fileName.equals(fileNames[i].getName())) {
                return true;
            }
        }

        return false;
    }

    /**
     * 删除文件夹、文件夹里面的文件
     *
     * @param file
     */
    public static void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                deleteFile(f);
            }
            file.delete();//删除文件夹
        } else if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 拷贝文件
     *
     * @param in  输入文件
     * @param out 输出文件
     * @return
     * @throws Exception
     */
    public static final boolean copyFile(File in, File out) throws Exception {
        try {
            FileInputStream fis = new FileInputStream(in);
            FileOutputStream fos = new FileOutputStream(out);
            byte[] buf = new byte[1024];
            int i = 0;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
            fis.close();
            fos.close();
            return true;
        } catch (IOException ie) {
            ie.printStackTrace();
            return false;
        }
    }

    /**
     * 拷贝文件
     *
     * @param infile  输入字符串
     * @param outfile 输出字符串
     * @return
     * @throws Exception
     */
    public static final boolean copyFile(String infile, String outfile) throws Exception {
        try {
            File in = new File(infile);
            File out = new File(outfile);
            return copyFile(in, out);
        } catch (IOException ie) {
            ie.printStackTrace();
            return false;
        }

    }
}
